package com.hsnn.medstgmini.base.dict.controller;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hsnn.medstgmini.Constants;
import com.hsnn.medstgmini.base.dict.model.DicArea;
import com.hsnn.medstgmini.base.dict.model.form.DicAreaForm;
import com.hsnn.medstgmini.base.dict.service.DicAreaManager;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.util.Pagination;
/**
 * 
 *@category 地区字典管理
 *@author 邱磊
 *@date 2015年6月17日 下午9:32:42
 */
@Controller
@RequestMapping("/dicArea")
public class DicAreaController {

	private static final Logger log = Logger.getLogger(DicAreaController.class);
	
	@Autowired
	private DicAreaManager dicAreaManager;
	
	@Autowired
	private  HttpServletRequest request;

	/**
	 * 
	 *@category 跳向地区字典列表页面
	 *@author 邱磊
	 *@date 2015年6月17日 下午9:32:59
	 *@return
	 */
	@RequestMapping("/toList")
	public String getAllList(){
		return "/base/dict/areaList";
	}
	
	//获取地区字典列表
	@RequestMapping("/getDataList" )
	@ResponseBody
	public Pagination getDataInfo(){
		log.info("searchareacode=" + request.getParameter("serchareacode") + ", fatherAreaCode=" + request.getParameter("fatherAreaCode")
				+ ", status=" + request.getParameter("status"));
		Pagination page = new Pagination(request);
		page.getConditions().put("serchareacode", request.getParameter("serchareacode"));
		page.getConditions().put("fatherAreaCode", request.getParameter("fatherAreaCode"));
		page.getConditions().put("status", request.getParameter("status"));
		try {
			page = dicAreaManager.getdicAreaList(page);
		} catch (Exception e) {
			log.error("Failed to sear area", e);
		}
		return page;
	}
	
	/**
	 * 
	 *@category 启用停用（包含批量）
	 *@author 邱磊
	 *@date 2015年6月17日 下午9:35:03
	 *@return
	 */
	@RequestMapping("/batchSwitchStatus" )
	@ResponseBody
	public Pagination batchOper(){
		Pagination page = new Pagination();
		log.info("params = " + request.getParameter("param") + ", state=" + request.getParameter("state"));
		try {
			String[] ids = request.getParameter("param").split(",");
			SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
			
			int operCount = 0;
			for(int i = 0; i < ids.length; i++){
				DicArea dicArea = new DicArea();
				dicArea.setUpdateuserid(user.getId());
				dicArea.setAreaid(ids[i]);
				dicArea.setStatus(Integer.parseInt(request.getParameter("state")));
				operCount += dicAreaManager.changeStatus(dicArea);
			}
			page.setOperCount(operCount);
			page.setSuccess(true);
		} catch (NumberFormatException e) {
			log.error("Failed to do batch oper", e);
			page.setSuccess(false);
		}
		
		return page;
	}
	
	/**
	 * 
	 *@category 添加地区信息
	 *@author 邱磊
	 *@date 2015年6月17日 下午9:34:01
	 *@return
	 */
	@RequestMapping("/addDicArea")
	@ResponseBody
	public Pagination addDicArea(){
		
		log.info("areaId = " + request.getParameter("areaId") + ", areaName = " + request.getParameter("areaName")
				+ ", arFullName = " + request.getParameter("arFullName") + ", arShortName = " + request.getParameter("arShortName")
				+ ", fatherId = " + request.getParameter("fatherId") + ", operflag = " + request.getParameter("operflag"));
		
		Pagination page = new Pagination();
		SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
		page.getConditions().put("updUser", user.getId());
		
		if(StringUtils.isNotBlank(request.getParameter("areaId"))){
			page.getConditions().put("areaId", request.getParameter("areaId").trim());
		}
		if(StringUtils.isNotBlank(request.getParameter("areaName"))){
			page.getConditions().put("areaName", request.getParameter("areaName").trim());
		}
		if(StringUtils.isNotBlank(request.getParameter("arFullName"))){
			page.getConditions().put("arFullName", request.getParameter("arFullName").trim());
		}
		if(StringUtils.isNotBlank(request.getParameter("arShortName"))){
			page.getConditions().put("arShortName", request.getParameter("arShortName").trim());
		}
		
		if (StringUtils.isNotBlank(request.getParameter("fatherId"))) {
			page.getConditions().put("father", request.getParameter("fatherId").trim());
		} else {
			// 没有制定父级地区时，父级地区为国家
			page.getConditions().put("father", "000000");
		}
		
		try {
			if (!"add".equals(request.getParameter("operflag"))) {
				dicAreaManager.updateDicArea(page);
				page.setMsg("修改成功!");
				page.setSuccess(true);
			} else {
	            String areaAddId = UUID.randomUUID().toString();
	            page.getConditions().put("areaAddId", areaAddId);
            	DicAreaForm form = dicAreaManager.getDicAreaById(request.getParameter("areaId"));
            	if (null != form && null != form.getAreaId() && !"".equals(form.getAreaId())){
            		page.setMsg("编码不能重复!");
					page.setSuccess(false);
					return page;
            	}
            	dicAreaManager.addDicArea(page);
				page.setMsg("保存成功!");
				page.setSuccess(true);
			}
		} catch (Exception e) {
			log.error("保存失败!", e);
			page.setMsg("保存失败!");
			page.setSuccess(false);
		}
		return page;
	}

	/**
	 * 
	 *@category 获取地区信息详情
	 *@author 邱磊
	 *@date 2015年6月17日 下午9:33:42
	 *@return
	 */
	@RequestMapping("/getData" )
	@ResponseBody
	public DicAreaForm getDicAreaById(){
		log.info("areaid = " + request.getParameter("areaid"));
		String areaid = request.getParameter("areaid");
		return dicAreaManager.getDicAreaById(areaid);
	}
}